import axios from "axios";

// 创建一个axios对象出来
const request = axios.create({
  baseURL: "http://localhost:8080",
  timeout: 50000,
});

// request 拦截器
request.interceptors.request.use(
  (config) => {
    // 如果请求是上传文件，使用 FormData
    if (config.headers["Content-Type"] === "multipart/form-data") {
      // 不手动设置 Content-Type，浏览器会自动设置 multipart/form-data
      delete config.headers["Content-Type"];
    } else {
      // 否则设置为 JSON
      config.headers["Content-Type"] = "application/json;charset=utf-8";
    }

    const user = localStorage.getItem("user");
    if (user) {
      config.headers["token"] = JSON.parse(user).token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response 拦截器
request.interceptors.response.use(
  (response) => {
    let res = response.data;
    if (typeof res === "string") {
      res = res ? JSON.parse(res) : res;
    }
    return res;
  },
  (error) => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

export default request;
